use crate::controller;
use crate::controller::endpoint::{DeleteEndpoint, SyncEndpoint};
use std::sync::Arc;
use tokio_tungstenite::tungstenite::Utf8Bytes;

pub struct MessageHandler {
    endpoint_controller: Arc<controller::EndpointController>,
}

impl MessageHandler {
    pub fn new(endpoint_controller: Arc<controller::EndpointController>) -> Self {
        Self {
            endpoint_controller,
        }
    }
}

#[async_trait::async_trait]
impl wanmesh_server::http::client::watch::TextMessageHandler for MessageHandler {
    async fn handle(&self, message: Utf8Bytes) {
        log::debug!("接收到消息：{}", message);
        let event: wanmesh_common::dto::Event<Box<serde_json::value::RawValue>> =
            match serde_json::from_str(&message) {
                Ok(v) => v,
                Err(e) => {
                    log::error!("解析消息失败：{}", e);
                    return;
                }
            };
        match event.event_type.as_str() {
            wanmesh_server::dto::event::endpoint::EVENT_TYPE_SETUP => {
                let payload: wanmesh_server::dto::event::endpoint::SetupEventPayload =
                    match serde_json::from_str(event.payload.get()) {
                        Ok(v) => v,
                        Err(e) => {
                            log::error!("解析消息失败：{}", e);
                            return;
                        }
                    };

                if let Err(e) = self.endpoint_controller.sync(&payload).await {
                    log::error!("同步endpoint失败：{}", e);
                }
            }
            wanmesh_server::dto::event::endpoint::EVENT_TYPE_DELETE => {
                let payload: wanmesh_server::dto::event::endpoint::DeleteEventPayload =
                    match serde_json::from_str(event.payload.get()) {
                        Ok(v) => v,
                        Err(e) => {
                            log::error!("解析消息失败：{}", e);
                            return;
                        }
                    };

                if let Err(e) = self.endpoint_controller.delete(&payload).await {
                    log::error!("删除endpoint失败：{}", e);
                }
            }
            _ => {
                log::error!("不支持的事件：{}", event.event_type);
            }
        }
    }
}
